import S_request from '../../utils/requestService.js';
import CONFIG from '../../config.js';
import * as utils from '../../utils/util.js';
const app = getApp()
let formId = 0; //表单Id
let gameTitle = '' //渠道名字
Page({
  data: {
    gold_num: 0,
    userinfo: null,
    modalObj: {},
    taskList: null,
    displayNormal: "none",
    displayLogin: "none",
    isShowNetWork: false,
    isShowGY: false,
    myStyle: '',
    allStyle: '',
    zlMyList: [],
    ismyBottom:true,

    page: 1,
    pageSize: 20,
    hasMoreData: false,
    zlAllList: [],
    gy_total: 0,
  },
  onShareAppMessage: function(res) {
    wx.showShareMenu({
      withShareTicket: false,
      success: function () { }
    });
    let obj = { 'pagepath': CONFIG.SHARE.path }
    S_request.index.recordShare("-1", obj);
    console.log("sharePath====" + CONFIG.SHARE.path)
    let title = '', imageUrl = '';
    if (gameTitle == '即有爱•公益中心') {
      let nickname = '亲，'
      if (app.globalData.userInfo != null) {
        nickname = app.globalData.userInfo.nickName;
      }
      title = nickname + "邀请你来为即有爱·公益事业助力。"
      imageUrl = CONFIG.SHARE.gyImageUrl
    } else {
      title = CONFIG.SHARE.title
      imageUrl = CONFIG.SHARE.imageUrl
    }
    return {
      title: title,
      path: CONFIG.SHARE.path,
      imageUrl: imageUrl
    }
  },
  onLoad: function() {
    this.getSetting();
    this.showGY();
  },
  setStyle: function() {
    let myStyle = 'color:#f65d00; border:1px solid #f65d00;'
    let allStyle = 'color:#999; border:1px solid #999;'
    this.setData({
      myStyle: myStyle,
      allStyle: allStyle,
      ismyBottom:true,
    })
    S_request.gy.getMyZhuli((result) => {
      if (result.lists == null) {
        this.setData({
          zlList: [],
          gy_total: result.total,
          hasMoreData: false
        })
        return;
      } else {
        for (let i = 0; i < result.lists.length; i++) {
          let list = result.lists[i];
          list.time = utils.formatTime(list.create_time, 3);
        }
        let scrollHeight = '';
        if (result.lists.length > 6) {
          scrollHeight = 'height:520rpx'
        } else {
          scrollHeight = '';
        }
        this.setData({
          zlList: result.lists,
          gy_total: result.total,
          scrollHeight: scrollHeight,
          hasMoreData: false
        })
      }
    })
  },
  myZhuli: function() {
    this.setStyle();
  },

  allZhuli: function() {
    let myStyle = 'color:#f65d00; border:1px solid #f65d00;'
    let allStyle = 'color:#999; border:1px solid #999;'
    this.setData({
      myStyle: allStyle,
      allStyle: myStyle,
      ismyBottom: false
    })
    S_request.gy.getAllZhuli(this.data.page, (result) => {
      let zlAllList = this.data.zlAllList;
      if (result.page == 1) {
        zlAllList = []
      } else {
        // 隐藏加载框
        wx.hideLoading();
      }
      if (result.lists.length < this.data.pageSize) {
        zlAllList = zlAllList.concat(result.lists);
        this.setData({
          hasMoreData: false
        })
      } else {
        zlAllList = zlAllList.concat(result.lists);
        this.setData({
          hasMoreData: true,
          page: this.data.page + 1
        })
      }
      for (let i = 0; i < zlAllList.length; i++) {
        let list = zlAllList[i];
        list.time = utils.formatTime(list.create_time, 3);
        if(list.nickname == '') {
          list.nickname = 'null'
        }
      }
      let scrollHeight = '';
      if (zlAllList.length > 6) {
        scrollHeight = 'height:520rpx;'
      } else {
        scrollHeight = '';
      }
      this.setData({
        zlList: zlAllList,
        gy_total: result.total,
        scrollHeight: scrollHeight,
        zlAllList: zlAllList
      })
    })
  },
  loadMore: function () {
    console.log("hasMoreData==" + this.data.hasMoreData)
    if (this.data.hasMoreData) {
      wx.showLoading({
        title: '玩命加载中',
        mask: true
      })
      this.allZhuli();
    } else {
      if (this.data.page != 1) {
        wx.showToast({
          title: '没有更多数据',
        })
      }
    }
  },
  showGY: function() {
    //实现渠道定制，动态修改标题名字
    gameTitle = wx.getStorageSync("gameTitle");
    if (gameTitle == '即有爱•公益中心') {
      this.setData({
        isShowGY: true,
        authStyle:'top: 46%'
      })
      this.setStyle();
    } else {
      this.setData({
        isShowGY: false,
        authStyle: 'top: 55%'
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getTaskList();
    this.setStyle();
  },
  getTaskList: function() {
    if (gameTitle == '即有爱•公益中心')return;
    S_request.mine.getTaskList((data) => {
      let tasks = data.tasks;
      let taskNum = 0;
      for (let i = 0; i < tasks.length; i++) {
        let item = tasks[i];
        item.navDisplay = 'none';
        item.viewDiaplay = 'block';
        if (item.id == 99) {
          item.title = "(" + data.completed + "/" + data.total + ") " + item.name;
          item.gold = item.goldcoin + "金币"
          if (item.status == 0) { //未完成
            item.color = '#f81b4a';
            item.btnTit = '进行中'
            item.touchEnable = false;
          } else if (item.status == 2) { //完成还未领取奖励
            item.color = '#f99122';
            item.btnTit = item.goldcoin + "金币";
            item.touchEnable = true;
          } else { //1:已领取奖励 
            item.color = '#21b4f7';
            item.btnTit = '已完成';
            item.touchEnable = false;
          }
        } else {
          item.title = item.name;
          item.gold = item.goldcoin + "金币"
          if (item.status == 0) { //未完成
            item.color = '#999';
            item.btnTit = "去完成" //item.goldcoin + "金币"
            if (item.action == 1 || item.action == 2) {
              item.touchEnable = true;
            } else {
              item.touchEnable = false;
            }
            if (item.action == 1) { //1:跳转到小游戏 2:跳转到详情页
              item.navDisplay = 'block';
              item.viewDiaplay = 'none';
            }
          } else if (item.status == 2) { //完成还未领取奖励
            item.color = '#f99122';
            item.btnTit = item.goldcoin + "金币"
            item.touchEnable = true;
          } else { //1:已领取奖励 
            item.color = '#21b4f7';
            item.btnTit = '已完成'
            item.touchEnable = false;
          }
        }

        if (item.status == 2) { //完成还未领取奖励
          taskNum++;
        }
      }
      console.log("taskNum====" + taskNum);
      app.globalData.goldnum = data.user.goldcoin;
      app.globalData.taskNum = taskNum;
      this.setData({
        taskList: tasks,
        gold_num: utils.parseGoldNum(data.user.goldcoin)
      })
    }, this)
  },
  getUserInfo: function() {
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo;
        this.setData({
          userinfo: app.globalData.userInfo,
        });
        S_request.index.updateUserInfo(res.userInfo, (result) => {
          // console.log("更新与用户信息成功====" + JSON.stringify(result));
          app.globalData.goldnum = result.goldcoin;
        })

        // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
        // 所以此处加入 callback 以防止这种情况
        if (this.userInfoReadyCallback) {
          this.userInfoReadyCallback(res)
        }
      }
    })
  },
  clickActivityIcon: function() {
    wx.navigateTo({
      url: '../activity/activity'
      // url: '../voiceRedPacket/index/index?redPackId=3'
    });
    // this.showModal();
  },
  clickAShopIcon: function() {
    wx.navigateTo({
      url: '../shop/shop'
    });
    // this.showModal();
  },
  clickChoujiangIcon: function() {
    wx.showModal({
      title: '提示',
      content: '敬请期待',
      showCancel: false
    })
    return
    wx.navigateTo({
      // url: '../choujiang/choujiang'
      url: '../duobao/index/index'
    });
    // this.showModal();
  },
  showModal: function() {
    this.data.modalObj.titS = '此功能暂未开启，敬请期待'
    this.data.modalObj.leftBtnStyle = "display:inline; background-color: #dc0000;border: 1px solid #c50101 !important";
    this.data.modalObj.confirm = "none"
    this.data.modalObj.imageStyle = "display:none";
    this.data.modalObj.titleStyle = "font-size:34rpx; color:#666";
    this.setData({
      modalDealIdx: 1,
      isShow: true,
      modalObj: this.data.modalObj
    })
  },
  modalLeftAc: function(e) {
    this.setData({
      modalDealIdx: 0,
      isShow: false
    })
  },
  playGame: function(e) {
    let id = e.currentTarget.dataset.id;
    console.log("id====" + id);
    let param = 'formId=' + formId
    S_request.index.tongJiNum(id, param, (result) => {
      console.log("data====" + result);
    })
  },
  getReward: function(e) {
    // wx.switchTab({  //跳转到 tabBar 页面
    //   url: 'pages/index/index'
    // })
    let isEnable = e.currentTarget.dataset.enable;
    if (!isEnable) return;
    let id = e.currentTarget.dataset.id;
    let action = e.currentTarget.dataset.action;
    let self = this;
    if (action == 2) {
      let gameId = '';
      for (let i = 0; i < this.data.taskList.length; i++) {
        let item = this.data.taskList[i];
        if (item.id == id) {
          gameId = item.progam.id;
          break;
        }
      }
      console.log("gameId===" + gameId);
      wx.navigateTo({
        url: '../detail/detail?gameId=' + gameId + "&type=play",
      })
    } else {
      S_request.mine.lingquReward(id, (data) => {
        console.log("领取成功数据===" + JSON.stringify(data))
        if (!data) return;
        self.lingquSuccess(data.goldcoin);
        S_request.index.updateUserInfo('', '', (result) => {
          app.globalData.goldnum = result.goldcoin;
          self.setData({
            gold_num: result.goldcoin
          });
        })
        self.getTaskList();
      })
    }
  },
  lingquSuccess: function(goldnum) {
    this.data.modalObj.titS = '+' + goldnum + "金币";
    this.data.modalObj.leftBtnStyle = "display:inline; background-color: #fec02b;border: 1px solid #ffb70a !important";
    this.data.modalObj.confirm = "none"
    this.data.modalObj.imageSrc = "../image/success_icon.png";
    this.data.modalObj.imageStyle = "display:block;margin-top:15px;height: 128px;width: 103px";
    this.data.modalObj.titleStyle = "font-size:17px; color:#f23e3d";
    this.setData({
      modalDealIdx: 1,
      isShow: true,
      modalObj: this.data.modalObj
    })
  },
  onGotUserInfo: function(e) {
    let self = this;
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    console.log(e.detail.rawData)
    if (!e.detail.userInfo) return;
    app.globalData.userInfo = e.detail.userInfo;
    let userInfo = e.detail.userInfo;
    S_request.index.updateUserInfo(userInfo, (result) => {
      // console.log("更新与用户信息成功====" + JSON.stringify(result));
      app.globalData.isAuthorize = true;
      self.setData({
        displayNormal: "block",
        displayLogin: "none",
        userinfo: app.globalData.userInfo,
        gold_num: utils.parseGoldNum(result.goldcoin)
      });
    })
  },
  showLoading: function() {
    wx.showLoading({
      title: '',
    })

    setTimeout(function() {
      wx.hideLoading()
    }, 1000)

  },
  getSetting: function() {
    let self = this;
    // 获取用户信息
    wx.getSetting({
      success: res => {
        var authSetting = res.authSetting;
        if (authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          app.globalData.isAuthorize = true;
          // this.showTabbar();
          this.getUserInfo();
        } else if (authSetting['scope.userInfo'] == false) {
          // 用户已拒绝授权，再调用相关 API 或者 wx.authorize 会失败，需要引导用户到设置页面打开授权开关
          app.globalData.isAuthorize = false;
          // this.showModal();
          // this.hiddenTabbar();
        } else {
          // 未询问过用户授权，调用相关 API 或者 wx.authorize 会弹窗询问用户
          app.globalData.isAuthorize = false;
          // this.showModal();
          // this.hiddenTabbar();
        }
        self.isShowLogin();
      }
    })
  },
  isShowLogin: function() {
    console.log("isAuthorize===" + app.globalData.isAuthorize)
    if (app.globalData.isAuthorize) {
      this.getUserInfo();
      this.getTaskList();
      this.setData({
        displayNormal: "block",
        displayLogin: "none"
      });
    } else {
      this.setData({
        displayNormal: "none",
        displayLogin: "block"
      });
    }
  },
  getNetworkStatus: function() {
    let self = this;
    //无网络时做提示no net
    wx.onNetworkStatusChange(function(res) {
      if (res.networkType == "none") {
        self.setData({
          isShowNetWork: true
        })
      } else {
        self.setData({
          isShowNetWork: false
        })
        self.getTaskList();
      }
    })
  },
  againLoadAc: function() {
    let self = this;
    wx.showLoading({
      title: '',
    })

    setTimeout(function() {
      wx.hideLoading()
      self.getSetting();
    }, 1000)
  },
  toKeGU: function() {

  },
  formSubmit: function(e) {
    formId = e.detail.formId;
    console.log('form发生了submit事件，携带数据为：', e.detail.value + ", " + e.detail.formId)
  },
  onReachBottom: function() {
  },
})